import os
import logging
import traceback

from seed_data import utils, table, api

LOG = logging.getLogger()
current_path = os.path.dirname(__file__)


def add_server_cfg(config, key, annotation=None, check_key=False):
    """
    向数据库增加配置信息
    :param config: 一条配置信息
    :param key: 哪个字段作为唯一标志（类如序列号，主机名，bmc地址）
    :param annotation: 输入的config的注释（例如10.228.2.10的硬件配置信息）
    :param check_key: 必须在原有数据上更新（主机配置excel页信息，依赖硬件配置excel页信息）
    :return:
    """
    if not hasattr(table.ServerCfg, key):
        raise Exception('DB ServerCfg table not have {}'.format(key))
    if 'key' not in config:
        config['key'] = key
    flat_config = utils.flat_dict(config)
    filter_dict = {key: config[key]}
    find_num = len(api.TabLeOperator(table.ServerCfg).get(filter_dict))
    if find_num > 0:
        if find_num > 1:
            raise Exception('{} table have {} repeat key:{}={}'.format(
                table.ServerCfg.__tablename__, find_num, key, config[key]))
        api.TabLeOperator(table.ServerCfg).update(flat_config,filter_dict)
    elif check_key:
        annotation = annotation or config[key]
        raise Exception('add {} to db failed, db must have {} data first'.format(
            annotation, config[key]))
    else:
        api.TabLeOperator(table.ServerCfg).add(flat_config)


def get_server_cfg(filters=None, annotation=None)->list:
    try:
        server_cfg = api.TabLeOperator(table.ServerCfg).get(filters)
        for i, v in enumerate(server_cfg):
            server_cfg[i] = utils.filter_dict_start_witch_(utils.merge_dict(v))
    except Exception as e:
        annotation = annotation or 'get data from table={} failed'.format(table.ServerCfg.__tablename__)
        raise Exception('{}, error={}, traceback={}'.format(annotation, str(e), traceback.format_exc()))
    else:
        return server_cfg

if __name__ == '__main__':
    input_dict = {'bmc': '1.1.1.1', 'ipmi': {'user': '1admin', 'password': '12345'}}
    update_dict = {'bmc': '1.1.1.2', 'ipmi': {'user': '1admin', 'password': '123456'}}
    add_server_cfg(input_dict, 'bmc')
    add_server_cfg(update_dict, 'bmc')
    all_server_cfg = get_server_cfg()
    print(all_server_cfg)
    server_cfg = get_server_cfg({'bmc':'1.1.1.1'})
    print(server_cfg)
